#!/usr/bin/env python
#coding: utf-8
#author: Wesley
import os
from django.conf.urls import url

from apps.general.handlers import stats, school
from .handlers import user
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

Error_Not_Login = JsonResponse({'retcode': 99, 'msg': '未登录'})


def CheckUserIsParentForApiCaller(request, *args, **kwargs):
    if 'ut' not in request.session:
        return Error_Not_Login

    realCall = kwargs.pop('_viewFunc')
    return realCall(request, *args, **kwargs)


def CheckForApiCaller(request, *args, **kwargs):
    realCall = kwargs.pop('_viewFunc')
    return realCall(request, *args, **kwargs)



urlpatterns_api = []

def addPreCheck(urlpatterns,checkFunC):
    # checkFunC = csrf_exempt(checkFunC)
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


csrf_exempt_api = []

def add_csrf_exempt_pre_check(urlpatterns, checkFunC):
    checkFunC = csrf_exempt(checkFunC)
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                csrf_exempt_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


urlpatterns_api_agrs = [
    ([r'^stats/$'], stats.handler.dispatch),
    ([r'^yj_schools/$'], school.handler.dispatch),
]

addPreCheck(urlpatterns_api_agrs, CheckUserIsParentForApiCaller)

csrf_exempt_urlpatterns_api_agrs = [
    ([r'^user/$'], user.handler.dispatch),
]

add_csrf_exempt_pre_check(csrf_exempt_urlpatterns_api_agrs, CheckForApiCaller)

urlpatterns = urlpatterns_api + csrf_exempt_api
